package com.yequan.leetcode.lrucache.LRUCache_146;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yequan
 * @date 2021/10/12 18:07
 **/
public class Recode4LRUCache {

    private Map<Integer, DBListNode> cache;
    private DBListNode head, tail;
    private int capacity;
    private int size;

    Recode4LRUCache(int capacity) {
        this.capacity = capacity;
        this.size = 0;
        cache = new HashMap<>();
        head = new DBListNode();
        tail = new DBListNode();
        head.next = tail;
        tail.pre = head;
    }

    int get(int key) {
        DBListNode node = cache.get(key);
        if (node == null) {
            return -1;
        }
        move2Head(node);
        return node.value;
    }

    void put(int key, int value) {
        DBListNode node = cache.get(key);
        if (node == null) {
            node = new DBListNode(key, value);
            cache.put(key, node);
            add2Head(node);
            if (++size > capacity) {
                DBListNode tailNode = removeTail();
                cache.remove(tailNode.key);
                --size;
            }
        } else {
            node.value = value;
            move2Head(node);
        }
    }

    private DBListNode removeTail() {
        DBListNode tailNode = tail.pre;
        removeNode(tailNode);
        return tailNode;
    }

    private void move2Head(DBListNode node) {
        removeNode(node);
        add2Head(node);
    }

    private void add2Head(DBListNode node) {
        head.next.pre = node;
        node.next = head.next;
        head.next = node;
        node.pre = head;
    }

    private void removeNode(DBListNode node) {
        node.next.pre = node.pre;
        node.pre.next = node.next;
    }

    public static class DBListNode {
        DBListNode pre;
        DBListNode next;
        int key;
        int value;

        public DBListNode() {
        }

        public DBListNode(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }

}
